package com.mypro.mydemo1.demo;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/Login")
public class Login extends HttpServlet {
    Connection conn;
    public void init() {
        String driver = "com.mysql.cj.jdbc.Driver";
        String dburl = "jdbc:mysql://localhost:3306/postgres";
        String username = "root";
        String password = "123456";
        try{

            Class.forName(driver);
            conn = DriverManager.getConnection(dburl,username,password);
        }catch(ClassNotFoundException |SQLException cfe){
            log("Exception:"+cfe);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;utf-8");
        String sno = request.getParameter("sno");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        try{
            String sql="SELECT * FROM student WHERE sno=? and password=?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,sno);
            pstmt.setString(2,password);
            ResultSet rst = pstmt.executeQuery();
            if(rst.next()){
                out.print("登录成功");
            }else{
                out.print("登录失败");
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    public void destroy(){
        try {
            conn.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
